package com.abu.classes.service.impl;

import com.abu.classes.pojo.Classes;
import com.abu.classes.mapper.ClassesMapper;
import com.abu.classes.service.ClassesService;
import com.abu.classes.utils.PageUtils;
import com.abu.common.exception.CRException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 班级表 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2021-05-07
 */
@Service
public class ClassesServiceImpl extends ServiceImpl<ClassesMapper, Classes> implements ClassesService {

    @Override
    public PageUtils queryByConditon(Long page, Long limit, String key) {
//        查询条件
        QueryWrapper<Classes> classesQueryWrapper = new QueryWrapper<>();
        classesQueryWrapper.
                eq(StringUtils.isNotBlank(key), "class_name", key)
                .or()
                .eq(StringUtils.isNotBlank(key), "instructor_name", key)
                .select("class_name", "class_id", "instructor_name", "update_time");
//        执行查询
        Page<Classes> classesPage = new Page<>(page, limit);
        Page<Classes> pageResult = this.page(classesPage, classesQueryWrapper);
        List<Classes> classesList = pageResult.getRecords();
        if (CollectionUtils.isEmpty(classesList)) {
            throw new CRException("数据为空");
        }
        return new PageUtils(classesPage);
    }

    @Override
    public Boolean saveClasses(Classes classes) {
        String className = classes.getClassName();
//        班级查询
        Classes classByQuery = this.getOne(new QueryWrapper<Classes>().eq("class_name", className));
        if (classByQuery != null) {
            throw new CRException("班级已存在，请更换班级名");
        }
//        班级保存
        return this.save(classes);
    }

    @Override
    public List<Classes> queryAllClasses() {
        return this.list(new QueryWrapper<Classes>().select("class_id", "class_name"));
    }
}
